const { v4: uuidv4 } = require("uuid");
const bcrypt = require("bcryptjs");
const jwt = require("../utils/jwt");
const { query } = require("../utils/db");

// 用户注册
exports.registerUser = async ({ FUsername, FPassword, FEmail }) => {
  // 检查用户名和邮箱是否已存在
  const [existingUsers] = await query(
    "SELECT FUserId FROM t_users WHERE FUsername = ? OR FEmail = ? LIMIT 2",
    [FUsername, FEmail]
  );

  if (existingUsers.some((user) => user.FUsername === FUsername)) {
    throw { status: 400, message: "用户名已存在" };
  }
  if (existingUsers.some((user) => user.FEmail === FEmail)) {
    throw { status: 400, message: "邮箱已存在" };
  }

  // 创建用户
  const FUserId = uuidv4();
  const hashedPassword = await bcrypt.hash(FPassword, 10);

  await query(
    `INSERT INTO t_users 
     (FUserId, FUsername, FPassword, FEmail, FIsActive)
     VALUES (?, ?, ?, ?, 1)`,
    [FUserId, FUsername, hashedPassword, FEmail]
  );

  return { FUserId, FUsername, FEmail };
};

// 用户登录
exports.loginUser = async ({ FUsername, FPassword, deviceInfo }) => {
  // 查询用户
  const [user] = await query(
    `SELECT FUserId, FUsername, FPassword, FEmail, FAvatar, FIsActive 
     FROM t_users WHERE FUsername = ? LIMIT 1`,
    [FUsername]
  );

  if (!user) {
    throw { status: 400, message: "用户名或密码错误" };
  }

  // 检查用户状态
  if (!user.FIsActive) {
    throw { status: 400, message: "账号已被禁用" };
  }

  // 验证密码
  if (!(await bcrypt.compare(FPassword, user.FPassword))) {
    throw { status: 400, message: "用户名或密码错误" };
  }

  // 生成双Token
  const { accessToken, refreshToken, tokenId } = await jwt.generateTokens(
    {
      FUserId: user.FUserId,
      FUsername: user.FUsername,
    },
    deviceInfo
  );

  // 记录登录历史
  await query(
    `INSERT INTO t_user_login_history 
     (FId, FUserId, FDeviceInfo) 
     VALUES (?, ?, ?)`,
    [uuidv4(), user.FUserId, deviceInfo]
  );

  return {
    access_token: accessToken,
    refresh_token: refreshToken,
    tokenId,
    FUserId: user.FUserId,
    FUsername: user.FUsername,
    FEmail: user.FEmail,
    FAvatar: user.FAvatar,
  };
};

// 检查登录状态
exports.checkAuthStatus = async (FUsername, FPassword) => {
  const [user] = await query(
    `SELECT FUserId, FUsername, FPassword, FEmail, FAvatar, FIsActive 
     FROM t_users WHERE FUsername = ? LIMIT 1`,
    [FUsername]
  );

  if (!user) {
    throw { status: 400, message: "用户名或密码错误" };
  }

  // 检查用户状态
  if (!user.FIsActive) {
    throw { status: 400, message: "账号未启用" };
  }

  // 验证密码
  if (!(await bcrypt.compare(FPassword, user.FPassword))) {
    throw { status: 400, message: "用户名或密码错误" };
  }

  // 获取最近的有效登录信息（未退出的）
  const [activeSession] = await query(
    `SELECT FId, FDeviceInfo, FLoginAt 
     FROM t_user_login_history 
     WHERE FUserId = ? AND FLogoutAt IS NULL
     ORDER BY FLoginAt DESC 
     LIMIT 1`,
    [user.FUserId]
  );

  // 获取最近的登录信息（无论是否退出）
  const [latestLogin] = await query(
    `SELECT FDeviceInfo, FLoginAt, FLogoutAt
     FROM t_user_login_history 
     WHERE FUserId = ? 
     ORDER BY FLoginAt DESC 
     LIMIT 1`,
    [user.FUserId]
  );

  return {
    isLogin: activeSession ? true : false,
    userInfo: {
      FUserId: user.FUserId,
      FUsername: user.FUsername,
      FEmail: user.FEmail,
      FAvatar: user.FAvatar,
    },
    activeSession: activeSession
      ? {
          sessionId: activeSession.FId,
          device: activeSession.FDeviceInfo,
          loginTime: activeSession.FLoginAt,
        }
      : null,
    latestLogin: latestLogin
      ? {
          device: latestLogin.FDeviceInfo,
          loginTime: latestLogin.FLoginAt,
          logoutTime: latestLogin.FLogoutAt,
          status: latestLogin.FLogoutAt ? "已退出" : "活跃中",
        }
      : null,
  };
};

// 用户注销
exports.logoutUser = async (FUserId, tokenId) => {
  // 标记Token为已撤销
  await query(
    "UPDATE t_user_tokens SET FIsRevoked = 1 WHERE FUserId = ? AND FId = ?",
    [FUserId, tokenId]
  );

  // 记录登出时间
  await query(
    `UPDATE t_user_login_history 
     SET FLogoutAt = CURRENT_TIMESTAMP 
     WHERE FUserId = ? 
     ORDER BY FLoginAt DESC 
     LIMIT 1`,
    [FUserId]
  );
};

// 获取当前用户信息
exports.getUserInfo = async (FUserId) => {
  const [user] = await query(
    `SELECT FUserId, FUsername, FEmail, FAvatar 
     FROM t_users WHERE FUserId = ? LIMIT 1`,
    [FUserId]
  );

  if (!user) {
    throw { status: 400, message: "用户不存在" };
  }

  return user;
};